﻿using FaceRecognitionDemo.Data;
using FaceRecognitionDemo.Models;
using Microsoft.EntityFrameworkCore;

namespace FaceRecognitionDemo.Services;

public class DomainService
{
    private readonly FaceDatabase _db;

    public DomainService(FaceDatabase db)
    {
        _db = db;
    }

    // 通用CRUD方法
    public async Task<T> AddAsync<T>(T entity, Func<T, bool> existsCheck) where T : class
    {
        if (existsCheck(entity))
            //throw new Exception("记录已存在");
            return entity;
            
        await _db.Set<T>().AddAsync(entity);
        var id =await _db.SaveChangesAsync();
        return entity;
    }

    public async Task UpdateAsync<T>(T entity) where T : class
    {
        _db.Set<T>().Update(entity);
        await _db.SaveChangesAsync();
    }

    public async Task DeleteAsync<T>(T entity) where T : class
    {
        _db.Set<T>().Remove(entity);
        await _db.SaveChangesAsync();
    }
    
    public async Task<T> GetAsync<T>(int id) where T : class
    {
        return await _db.Set<T>().FindAsync(id);
    }
    
    public async Task<List<T>> GetListAsync<T>() where T : class
    {
        return await _db.Set<T>().ToListAsync();
    }
    
    public async Task<Person> GetPerson(int id)
    {
        return await GetAsync<Person>(id);
    }
    
    public async Task<Person> GetPerson(string name)
    {
        return await _db.Set<Person>().FirstOrDefaultAsync(x => x.Name == name);
    }

    // 具体实体操作方法
    public async Task<Person> AddPerson(Person person)
    {
        return await AddAsync(person, p => _db.Persons.Any(x => x.Name == person.Name));
    }

    public async Task<Face> AddFace(Face face)
    {
        return await AddAsync(face, f => _db.Faces.Any(x => x.ImageHash == face.ImageHash));
    }

    // 其他查询方法...
}